package com.itzjc.controller;

import com.itzjc.domain.entity.RequestUser;
import com.itzjc.domain.entity.Result;
import com.itzjc.domain.pojo.User;
import com.itzjc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * TODO
 *
 * @className: UserController
 * @date: 2021-06-10 09:13
 **/
@RestController
@RequestMapping("/web/api/v1/pri/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/findById")
    public Result findById(int id) {
        User user = userService.findById(id);
        return Result.buildSuccess("查询成功", user);
    }

    @PostMapping("/login")
    public Result login(@RequestBody RequestUser requestUser) {
        User user = userService.login(requestUser.getPhone(), requestUser.getPassword());
        return (user.getToken()  =="0") ? Result.buildError("账户或密码错误，登录失败", 300) : Result.buildSuccess("登录成功", user);
    }

    @PostMapping("/register")
    public Result register(@RequestBody RequestUser requestUser) {
        String username = userService.register(requestUser);
        return null == username ? Result.buildError("注册失败，请重试", 300) : Result.buildSuccess("注册成功", username);
    }

    @PostMapping("/phoneNumberIsOk")
    public Result phoneNumberIsOk(@RequestBody RequestUser requestUser) {
        String username = userService.phoneNumberIsOk(requestUser);
        return null == username ? Result.buildError("手机号占用，注册失败，请重试", 300) : Result.buildSuccess("注册成功", username);
    }

    @PostMapping("/forget")
    public Result forget(@RequestBody RequestUser requestUser) {
        String phone = userService.forget(requestUser);
        return Result.buildSuccess("修改成功", phone);
    }

    @GetMapping("/userInfoByToken")
    public Result userInfoByToken(HttpServletRequest request){
        Integer userId = (Integer) request.getAttribute("user_id");
        if (null == userId) {
            return Result.buildError("用户没有登录", 300);
        }
        User user=userService.userInfoByToken(userId);
        return Result.buildSuccess("获取用户信息成功",user);
    }
}
